//
// Created by 215609 on 2024/7/2.
//

#include "TSFFmpeg.h"
#include "AndroidLog.h"

TSFFmpeg::TSFFmpeg(TSPlayerStatus *mTSPlayerStatus, TsCallJava *callJava, const char *_url) {
    this->mTSPlayerStatus=mTSPlayerStatus;
    this->callJava=callJava;
    this->url=_url;
    LOGE("cant not open TSFFmpeg strames %s",url);
    pthread_mutex_init(&seek_mutex, nullptr);
}


void TSFFmpeg::pasue() {
    if (mTSAudio!=nullptr){
        mTSAudio->pause();
    }
}

void TSFFmpeg::resume() {
    if(mTSAudio != nullptr)
    {
        mTSAudio->resume();
    }
}

void TSFFmpeg::seek(int secds) {
    if (duration<=0){
        return;
    }
    if (secds>=0&&secds<=duration){

        //上锁
        pthread_mutex_lock(&seek_mutex);

        if (mTSAudio!= nullptr){
            mTSPlayerStatus->seek= true;
            mTSAudio->queue->clearAvpacket();
            mTSAudio->clock=0;
            mTSAudio->last_tiem=0;
//      --------------------------------------------------
            int64_t rel=secds*AV_TIME_BASE;
            avformat_seek_file(avFormatContext,-1,
                               INT64_MIN,rel,INT64_MAX,0);
//      --------------------------------------------------
            mTSPlayerStatus->seek= false;
        }
        pthread_mutex_unlock(&seek_mutex);
    }
}

void TSFFmpeg::decodeFFmpegThread() {
     avformat_network_init();

     avFormatContext=avformat_alloc_context();
    LOGE("can not open url1112 :%s", url);

    int ret=avformat_open_input(&avFormatContext,url, nullptr,nullptr);
    if (ret!=0){
        if(LOG_DEBUG){
            LOGE("can not open url2323 :%s %d", url,ret);
        }
        return;
    }

    if (avformat_find_stream_info(avFormatContext,nullptr)<0){
        if(LOG_DEBUG){
            LOGE("can not find streams from %s", url);
        }
        return;
    }

    for (int i = 0; i < avFormatContext->nb_streams; ++i){
        LOGE("--2-----rere- nb_streams --%d--->77 %d %d",i,avFormatContext->streams[i]->codecpar->codec_type,AVMEDIA_TYPE_AUDIO);
        if (avFormatContext->streams[i]->codecpar->codec_type==AVMEDIA_TYPE_AUDIO){
            LOGE("--2--ewew---rereeee--dsd---->77");
            if (mTSAudio== nullptr){
                LOGE("--2-----rereeee--dsd---->77");
                mTSAudio=new TSAudio(mTSPlayerStatus,
                                     avFormatContext->streams[i]->codecpar->sample_rate
                                     ,callJava);
                mTSAudio->streamIndex=i;
                LOGE("--2-----rere--dsd---->77");
                //编码
                mTSAudio->codecpar= avFormatContext->streams[i]->codecpar;
                //单位时间的刻度
                mTSAudio->time_base=avFormatContext->streams[i]->time_base;
                //
                mTSAudio->duration = avFormatContext->duration/ AV_TIME_BASE;
                duration = mTSAudio->duration;
            }
        }
    }
    //查找编码器
    LOGE("--2----------->77");
    LOGE("------------->77888 %d",avFormatContext->streams[ mTSAudio->streamIndex]->codecpar->codec_id);
    AVCodec *dec= avcodec_find_decoder(avFormatContext->streams[ mTSAudio->streamIndex]->codecpar->codec_id);
    LOGE("------------->77");
    if(!dec){
        if(LOG_DEBUG){
            LOGE("can not find decoder");
        }
        return;
    }
    mTSAudio->avCodecContext= avcodec_alloc_context3(dec);
    if(!mTSAudio->avCodecContext){
        if(LOG_DEBUG){
            LOGE("can not alloc new decodec context");
        }
        return;
    }
    if (avcodec_parameters_to_context(mTSAudio->avCodecContext,mTSAudio->codecpar)){
        if(LOG_DEBUG){
            LOGE("can not fill decodecctx");
        }
        return;
    }

    if(avcodec_open2(mTSAudio->avCodecContext,dec,0)){
        if(LOG_DEBUG){
            LOGE("cant not open audio strames");
        }
        return;
    }
    LOGE("-------------> success");
    callJava->onCallParpared(CHILD_THREAD);
}

TSFFmpeg::~TSFFmpeg() {

}

void TSFFmpeg::start() {
    LOGD("audio is null222");
    if(mTSAudio == NULL)
    {
        if(LOG_DEBUG)
        {
            LOGD("audio is null");
            return;
        }
    }
    mTSAudio->play();
    int count=0;
    while (mTSPlayerStatus!=NULL&&!mTSPlayerStatus->exit){
        if (mTSPlayerStatus->seek){
            continue;
        }
        //放入队列
        if (mTSAudio->queue->getQueueSize()>40){
            continue;
        }
        AVPacket *avPacket = av_packet_alloc();
        LOGD("audio is AVPacket");
        if (av_read_frame(avFormatContext,avPacket)==0){
            if (avPacket->stream_index==mTSAudio->streamIndex){

                LOGD("audio is AVPacket %d",mTSAudio->queue->size());
                mTSAudio->queue->putAvpacket(avPacket);
            }else{
                av_packet_free(&avPacket);
                av_free(avPacket);
            }
            LOGD("audio is av_read_frame");
        }else{
            av_packet_free(&avPacket);
            av_free(avPacket);
            while(mTSPlayerStatus!= nullptr&&!mTSPlayerStatus->exit){
                if (mTSAudio->queue->getQueueSize()>0){
                    continue;
                }else{
                    mTSPlayerStatus->exit = true;
                    break;
                }
            }
        }
        if(mTSPlayerStatus != nullptr && mTSPlayerStatus->exit)
        {
            mTSAudio->queue->clearAvpacket();
            mTSPlayerStatus->exit = true;
        }
    }
}



void TSFFmpeg::setMute(jint mute) {
    if(mTSAudio != nullptr){
        mTSAudio->setMute(mute);
    }
}

void *decodeFFmpeg(void *data)
{
    TSFFmpeg *mnFFmpeg = (TSFFmpeg *) data;
    LOGE("decodeFFmpeg %s",mnFFmpeg->url);
    mnFFmpeg->decodeFFmpegThread();
    pthread_exit(&mnFFmpeg->decodeThread);
}
void TSFFmpeg::prepare() {
    LOGE("cant not open audio strames %s",url);
    pthread_create(&decodeThread,nullptr,
                   decodeFFmpeg,this);
}